package com.justplay.mobilelocation;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;

import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.InstrumentationRegistry.getContext;
import static org.junit.Assert.assertEquals;

/**
 * Instrumentation test, which will execute on an Android device.
 *
 * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    @Test
    public void useAppContext() throws Exception {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();

        assertEquals("com.justplay.mobilelocation", appContext.getPackageName());
    }

    @Test
    public void testContact() throws Exception {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();

        assertEquals("com.justplay.mobilelocation", appContext.getPackageName());
    }


    private static final String TAG = "ContactsTest";

    //获取所有联系人
    @Test
    public void testContacts() throws Exception {
        Uri uri = Uri.parse("content://com.android.contacts/contacts");
        ContentResolver resolver = getContext().getContentResolver();
        Cursor cursor = resolver.query(uri, new String[]{"_id"}, null, null, null);
        while (cursor.moveToNext()) {
            int contactid = cursor.getInt(0);
            StringBuilder sb = new StringBuilder("contactid=");
            sb.append(contactid);
            uri = Uri.parse("content://com.android.contacts/contacts/" + contactid + "/data");
            Cursor datacursor = resolver.query(uri, new String[]{"mimetype", "data1", "data2"}, null, null, null);
            while (datacursor.moveToNext()) {
                String data = datacursor.getString(datacursor.getColumnIndex("data1"));
                String type = datacursor.getString(datacursor.getColumnIndex("mimetype"));
                if ("vnd.android.cursor.item/name".equals(type)) {//姓名
                    sb.append(",name=" + data);
                } else if ("vnd.android.cursor.item/email_v2".equals(type)) {//email
                    sb.append(",email=" + data);
                } else if ("vnd.android.cursor.item/phone_v2".equals(type)) {//phone
                    sb.append(",phone=" + data);
                }
            }
            Log.i(TAG, sb.toString());
            System.out.println(sb.toString());
            assertEquals("com.justplay.mobilelocation", sb.toString());

        }
    }
}
